package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.macro.mall.common.enums.LoginTypeEnum;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.util.RequestUtil;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberLoginLogMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.LoginParam;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.domain.wechat.WeChatResult;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.service.WeChatService;
import com.macro.mall.portal.sms.SmsMessageService;
import com.macro.mall.security.util.JwtTokenUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 会员管理Service实现类
 *
 * @author macro
 * @date 2018/8/3
 */
@Service
@AllArgsConstructor
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    private PasswordEncoder passwordEncoder;
    private JwtTokenUtil jwtTokenUtil;
    private UmsMemberMapper memberMapper;
    private UmsMemberLevelMapper memberLevelMapper;
    private UmsMemberCacheService memberCacheService;
    private SmsMessageService smsMessageService;
    private UmsMemberLoginLogMapper umsMemberLoginLogMapper;
    private WeChatService weChatService;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if (member != null) {
            return member;
        }
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    /**
     * 判断该手机号是否存在，如果存在返回该用户信息
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public UmsMember getMemberByPhone(String phoneNumber) {
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(phoneNumber);
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        return !CollectionUtils.isEmpty(umsMembers) ? umsMembers.get(0) : null;
    }

    /**
     * 判断该openId是否存在，如果存在则返回该用户信息
     *
     * @param openId
     * @return
     */
    @Override
    public UmsMember getMemberByOpenId(String openId) {
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andOpenIdEqualTo(openId);
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        return !CollectionUtils.isEmpty(umsMembers) ? umsMembers.get(0) : null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            Asserts.fail("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        try {
            boolean success = smsMessageService.sendMessage(telephone, sb.toString());
            if (success) {
                memberCacheService.setAuthCode(telephone, sb.toString(), smsMessageService.getExpireTimeSecond());
                return sb.toString();
            }
        } catch (TencentCloudSDKException e) {
            LOGGER.error("生成验证码失败：" + e.getMessage(), e);
        }
        return "";
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            Asserts.fail("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getUmsMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UmsMember loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if (member != null) {
            return member;
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    private String existsOrRegister(UmsMember umsMemberExists, LoginParam loginParam, String openId) {
        String token = "";
        if (Objects.nonNull(umsMemberExists)) {
            MemberDetails userDetails = new MemberDetails(umsMemberExists);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } else {
            //不存在，说明需要注册该用户，且密码默认为用户手机号码
            UmsMember umsMember = new UmsMember();
            umsMember.setUsername(loginParam.getPhone());
            umsMember.setPhone(loginParam.getPhone());
            umsMember.setOpenId(openId);
            umsMember.setPassword(passwordEncoder.encode(loginParam.getPhone()));
            umsMember.setCreateTime(new Date());
            umsMember.setStatus(1);
            //获取默认会员等级并设置
            UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
            levelExample.createCriteria().andDefaultStatusEqualTo(1);
            List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
            if (!CollectionUtils.isEmpty(memberLevelList)) {
                umsMember.setMemberLevelId(memberLevelList.get(0).getId());
            }
            int insert = memberMapper.insert(umsMember);
            if (insert > 0) {
                umsMember.setPassword(null);
                MemberDetails memberDetails = new MemberDetails(umsMember);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(memberDetails, null, memberDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                token = jwtTokenUtil.generateToken(memberDetails);
            }
        }
        return token;
    }

    @Override
    public String login(LoginParam loginParam) {
        String token = null;
        UmsMember umsMemberGlobal = null;
        //密码需要客户端加密后传递
        if (LoginTypeEnum.WEIXIN.getCode().equals(loginParam.getLoginType())) {
            if (StrUtil.isBlank(loginParam.getWxCode())) {
                throw new ApiException("微信CODE不能为空");
            }
            WeChatResult weChatResult = weChatService.code2session(loginParam.getWxCode());
            if (StrUtil.isBlank(weChatResult.getOpenid())) {
                throw new ApiException("获取openid失败：" + weChatResult.getErrmsg());
            }
            UmsMember umsMemberExists = getMemberByOpenId(weChatResult.getOpenid());
            if (Objects.isNull(umsMemberExists)) {
                umsMemberExists = getMemberByPhone(loginParam.getPhone());
            }
            token = existsOrRegister(umsMemberExists, loginParam, weChatResult.getOpenid());
            umsMemberGlobal = umsMemberExists;
        }
        if (LoginTypeEnum.PASSWORD.getCode().equals(loginParam.getLoginType())) {
            try {
                UmsMember umsMember = loadUserByUsername(loginParam.getUsername());
                MemberDetails userDetails = new MemberDetails(umsMember);
                if (!passwordEncoder.matches(loginParam.getPassword(), userDetails.getPassword())) {
                    throw new BadCredentialsException("密码不正确");
                }
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                token = jwtTokenUtil.generateToken(userDetails);
                umsMemberGlobal = userDetails.getUmsMember();
            } catch (AuthenticationException e) {
                LOGGER.warn("登录异常:{}", e.getMessage());
            }
        }
        if (LoginTypeEnum.PHONEVERIFYCODE.getCode().equals(loginParam.getLoginType())) {
            //验证验证码
            if (!verifyAuthCode(loginParam.getVerifyCode(), loginParam.getPhone())) {
                Asserts.fail("验证码错误");
            }
            //1. 先查询该手机号对应用户是否存在，如果不存在，则注册
            UmsMember umsMemberExists = getMemberByPhone(loginParam.getPhone());
            //2. 如果存在则返回token
            token = existsOrRegister(umsMemberExists, loginParam, null);
            umsMemberGlobal = umsMemberExists;
        }
        //记录会员登录操作
        if (StrUtil.isNotBlank(token)) {
            UmsMemberLoginLog memberLoginLog = new UmsMemberLoginLog();
            if (Objects.nonNull(umsMemberGlobal)) {
                memberLoginLog.setMemberId(umsMemberGlobal.getId());
                memberLoginLog.setCreateTime(new Date());
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = null;
                if (attributes != null) {
                    request = attributes.getRequest();
                }
                if (request != null) {
                    memberLoginLog.setIp(RequestUtil.getRequestIp(request));
                }
                memberLoginLog.setCity(umsMemberGlobal.getCity());
                memberLoginLog.setLoginType(loginParam.getLoginType());
                memberLoginLog.setLoginWay(3);
                umsMemberLoginLogMapper.insertSelective(memberLoginLog);
            }
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone) {
        if (StrUtil.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
